﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PTA;

namespace PTA.Web
{
    public class EllipsisContainer : System.Web.UI.WebControls.Panel
    {
        private const string ellipsiscontainerjs = @"
            $(function ()
            {
                $('div.ellipsiscontainer')
                .each(function ()
                {
                    var me = $(this);
                    me.data('staticwidth', 0).data('xcellswidth', []).find('thead th')
                    .filter(':not([xwidth])').each(function () { me.data('staticwidth', me.data('staticwidth') + $(this).width()); }).end()
                    .filter('[xwidth]').each(function () { me.data('xcellswidth')[$(this)[0].cellIndex] = $(this).attr('xwidth'); });
                    ReviseContainer(me);
                }).filter(':not(.staticwidth)').each(function () { var me = $(this); $(window).resize(function () { ReviseContainer(me); }); });
                function ReviseContainer(c)
                {
                    var cellswidth = c.width() - c.data('staticwidth');
                    if (!(c.data('cellswidth') && (c.data('cellswidth') == cellswidth)))
                    {
                        var xcellswidth = c.data('cellswidth', cellswidth).data('xcellswidth');
                        c.find('tbody span.ellipsis').width(function () { $(this).width(cellswidth * xcellswidth[$(this).parent('td')[0].cellIndex]); });
                    }
                };
            });";

        protected override void OnPreRender(EventArgs e)
        {
            this.CssClass = string.Join(" ", this.CssClass ?? string.Empty, "ellipsiscontainer", StaticWidth ? "staticwidth" : string.Empty);
            if (!Page.ClientScript.IsClientScriptBlockRegistered(typeof(EllipsisContainer), "ellipsiscontainerjs"))
            {
                Page.ClientScript.RegisterClientScriptBlock(typeof(EllipsisContainer), "ellipsiscontainerjs", ellipsiscontainerjs, true);
            }
            
            base.OnPreRender(e);
        }

        /// <summary>
        /// 获取或设置一个值，指示这个控件的宽度是否是固定的,默认固定(true)
        /// </summary>
        public bool StaticWidth
        {
            get
            {
                return ViewState.GetBool("StaticWidth", true);
            }
            set
            {
                this.ViewState["StaticWidth"] = value;
            }
        }
    }
}
